var open_window = null;

var selected_blessing = null;

var setup_blessing_hover = function() {

    selected_blessing = null;

    $('.flower-image')
        .addClass('flower-background')
        .hover(function() {
            $(this).removeClass('flower-background');
            if(my_points >= 100) {
                $(this).addClass('click-to-buy');
            } else {
                $(this).addClass('not-enough-points');
            }
        },function() {
            $(this).removeClass('click-to-buy');    
            $(this).removeClass('not-enough-points');
            $(this).addClass('flower-background');
        })
        .click(function() {
            if(my_points >= 100) {
                selected_blessing = 'flower';
                showSendBlessing();
            }
        }
    );
    
    $('.turtle-image')
        .addClass('turtle-background')
        .hover(function() {
            $(this).removeClass('turtle-background');
            if(my_points >= 1000) {
                $(this).addClass('click-to-buy');
            } else {
                $(this).addClass('not-enough-points');
            }
        },function() {
            $(this).removeClass('click-to-buy');    
            $(this).removeClass('not-enough-points');
            $(this).addClass('turtle-background');
        })
        .click(function() {
            if(my_points >= 1000) {
                selected_blessing = 'turtle';
                showSendBlessing();
            }
        }
    );

    $('.car-image')
        .addClass('car-background')
        .hover(function() {
            $(this).removeClass('car-background');
            if(my_points >= 10000) {
                $(this).addClass('click-to-buy');
            } else {
                $(this).addClass('not-enough-points');
            }
            },function() {
                $(this).removeClass('click-to-buy');    
                $(this).removeClass('not-enough-points');
                $(this).addClass('car-background');
            })
        .click(function() {
            if(my_points >= 10000) {
                selected_blessing = 'car';
                showSendBlessing();
            }        
        }  
    );
}

var show_fbml_dialog = function (title, fbml, width, height) {
    try {
        open_window.close();
    } catch(e) {}
    var dlg = new FB.UI.FBMLPopupDialog(title, fbml, true, true);
    if (width) {
        width = parseInt(width);
        dlg.setContentWidth(width);
    }
    if (height) {
        height = parseInt(height);
        dlg.setContentHeight(height);
    }
    dlg.set_placement(FB.UI.PopupPlacement.topCenter);
    
    FB.CanvasClient.scrollTo(0,0);

    open_window = dlg;
    
    return dlg;
}


var showWitnessQuotaUsedUp = function() {
    show_fbml_dialog(
        'Can\'t Send Witness',
        '<h2 style="width:100%; padding-top: 20px; text-align:center;">You have used up you daily outgoing witness quota.<br/> Please wait until tomorrow to send another witness/prayer.</h2>',  
        470,
        120
    ).show();
}

var showEncourageQuotaUsedUp = function() {
    show_fbml_dialog(
        'Can\'t Send Encouragement',
        '<h2 style="width:100%; padding-top: 20px; text-align:center;">You have used up you daily outgoing encouragement quota.<br/> Please wait until tomorrow to send another encouragement.</h2>',  
        470,
        120
    ).show();
}

var showProblemSending = function() {
    show_fbml_dialog(
        'Problem',
        '<h2 style="width:100%; padding-top: 20px; text-align:center;">Problem sending your message.<br/><br/><br/><br/><div style="font-weight:normal">Please ensure the following:</div><br/>1. You chose a message recipient.<br/><br/><div style="font-weight:normal">and</div><br/>2. Your message is between 1 and 10,000 characters.<br/><br/><br/><br/><div style="font-weight:normal">If you have met both of these requirements and are still having problems,<br/>please contact us by clicking "Feedback" on the left side of this page.<br/><br/>Thank You,<br/>The BibleBeaters Team</div></h2>',  
        550,
        400
    ).show();
}

var showSuccessfullySent = function() {
    show_fbml_dialog(
        'Success',
        '<h2 style="width:100%; padding-top: 20px; text-align:center;">Your message was successfully delivered.</h2>',  
        400,
        100
    ).show();
}
        
var showSendBlessing = function() {
    if(selected_blessing) {
        $.facebox.close(); 
        show_fbml_dialog(
            'Bless a Friend',
            '<form action="http://'+host+'/" method="post">'+
                '<input type="hidden" name="gift" value="'+selected_blessing+'" />'+
                '<input type="hidden" name="action" value="bless" />'+
                '<table class="witness-table" style="width: 100%; padding: 30px;">'+
                    '<tr class="bless-row3" style="width: 100%">'+
                        '<td style="width: 43%">'+
                            '<h2>Step 2: (Optional) Type a message.</h2>'+
                        '</td>'+
                        '<td style="width: 33%">'+
                            '<h2>Step 3: Select a recipient.</h2>'+
                        '</td>'+
                        '<td style="width: 23%">'+
                            '<h2>Step 4: Send it.</h2>'+
                        '</td>'+
                    '</tr>'+
                    '<tr class="bless-row4">'+
                        '<td valign="top">'+
                            '<textarea rows=10 style="width:90%" name="bless_message">'+
                            '</textarea>'+
                        '</td>'+
                        '<td valign="top">'+
                            '<fb:friend-selector uid="'+uid+'" name="uid" idname="chosen_user_id" />'+
                        '</td>'+
                        '<td valign="top">'+
                            '<input type="submit" value="Send" />'+
                        '</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>You can write up to <b>10,000</b> characters.</td>'+
                    '</tr>'+
                '</table>'+
            '</form>',
            700,
            300
        ).show();
        FB.CanvasClient.scrollTo(0,0);            
    }
}
$(document).ready(function() {
    
    $('.invite-button').click(function() {
        show_fbml_dialog(
            'Invite Friends',
            '<fb:fbml><fb:request-form action="'+ document.location +'" method="POST" invite="true" type="BibleBeaters" content="' +
                'BibleBeaters wants to help you fulfill God\'s commandment of &quot;making disciples&quot;, and we feel that the best way we can help, is by being a tool for you to witness to your friends and family. With BibleBeaters you earn points for each witness, prayer, and encouragement you send to your friends, and then you use those points to buy gifts for them as well! Give BibleBeaters a try today, it\'s fun!<fb:req-choice url=\'http://apps.facebook.com/'+app_name+'/\' label=\'Try BibleBeaters\' />" ><fb:multi-friend-selector rows="2" cols="4" bypass="Cancel"'+
                ' exclude_ids="'+friends_that_have_biblebeaters+'" showborder="false" actiontext="Use this form to invite your friends to use BibleBeaters."/></fb:request-form></fb:fbml>',  
            660,
            670
        ).show();
    });
        
    $('.button').click(function() { 
        $(document.activeElement).blur();
    });    
        
    var fading_logo_in = false;
    var fading_logo_out = false;
    
    $('#logo').hover(function() {
        if(fading_logo_in) { return; }
        fading_logo_in = true;      
        $('#activity-description').fadeOut(400, function() { fading_activity_out = false; });            
        $('#logo-description').fadeIn(400, function() { fading_logo_in = false; });      
    },function() {
        if(fading_logo_out) { return; }
        fading_logo_out = true;              
        $('#logo-description').fadeOut(400, function() { fading_logo_out = false; });
    });
    
    var fading_activity_in = false;
    var fading_activity_out = false;
    
    $('#activity-level-contents').hover(function() {
        if(fading_activity_in) { return; }
        fading_activity_in = true;      
        $('#logo-description').fadeOut(400, function() { fading_logo_out = false; });            
        $('#activity-description').fadeIn(400, function() { fading_activity_in = false; });      
    },function() {
        if(fading_activity_out) { return; }
        fading_activity_out = true;              
        $('#activity-description').fadeOut(400, function() { fading_activity_out = false; });
    });
    
    $('#witness-button').click(function() {
        //setTimeout('$("input[name=uid]").focus();',2000);
        if(used_witness_quota) return showWitnessQuotaUsedUp();
        show_fbml_dialog(
            'Witness to a Friend',
            '<form action="http://'+host+'/" method="post">'+
                '<input type="hidden" name="action" value="witness" />'+
                '<table id="witness-table" style="width: 100%; padding: 30px;">'+
                    '<tr id="witness-row1" style="width: 100%">'+
                        '<td style="width: 43%">'+
                            '<h2>Step 1: Type a message.</h2>'+
                        '</td>'+
                        '<td style="width: 33%">'+
                            '<h2>Step 2: Select a recipient.</h2>'+
                        '</td>'+
                        '<td style="width: 23%">'+
                            '<h2>Step 3: Send it.</h2>'+
                        '</td>'+
                    '</tr>'+
                    '<tr id="witness-row2">'+
                        '<td valign="top">'+
                            '<textarea rows=10 style="width:90%" name="witness_message">'+
                            '</textarea>'+
                        '</td>'+
                        '<td valign="top">'+
                            '<fb:friend-selector uid="'+uid+'" name="uid" idname="chosen_user_id" />'+
                        '</td>'+
                        '<td valign="top">'+
                            '<input type="submit" value="Send" />'+
                        '</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>You can write up to <b>10,000</b> characters.</td>'+
                    '</tr>'+
                '</table>'+
            '</form>',  
            700,
            300
        ).show();
    });

    $('#bless-button').click(function() {                                    
        FB.CanvasClient.scrollTo(0,0);
        setTimeout('setup_blessing_hover();',1000);
    });

    $('#encourage-button').click(function() {
        if(used_encouragement_quota) return showEncourageQuotaUsedUp();
        show_fbml_dialog(
            'Encourage a Friend',
            '<form action="http://'+host+'/" method="post"><input type="hidden" name="action" value="encourage" /><table id="witness-table" style="width: 100%; padding: 30px;"><tr id="witness-row1" style="width: 100%"><td style="width: 43%"><h2>Step 1: Type a message.</h2></td><td style="width: 33%"><h2>Step 2: Select a recipient.</h2></td><td style="width: 23%"><h2>Step 3: Send it.</h2></td></tr><tr id="witness-row2"><td valign="top"><textarea rows=10 style="width:90%" name="encouragement_message" ></textarea></td><td valign="top"><fb:friend-selector uid="'+uid+'" name="uid" idname="chosen_user_id" /></td><td valign="top"><input type="submit" value="Send" /></td></tr><tr><td>You can write up to <b>10,000</b> characters.</td></tr></table></form>',
            700,
            300
        ).show();
    });
    
    ;(function($){ $.jgrid.extend({
        setGridState : function(state) {
            return this.each(function(){
                if ( !this.grid ) {return;}
                $t = this;
                if(state == 'hidden'){
                    $(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+$t.p.id).slideUp("fast");
                    if($t.p.pager) {$($t.p.pager).slideUp("fast");}
                    if($t.p.toolbar[0]===true) {
                        if( $t.p.toolbar[1]=='both') {
                            $($t.grid.ubDiv).slideUp("fast");
                        }
                        $($t.grid.uDiv).slideUp("fast");
                    }
                    if($t.p.footerrow) $(".ui-jqgrid-sdiv","#gbox_"+$s.p.id).slideUp("fast");
                    $(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
                    $t.p.gridstate = 'hidden';
                } else if(state=='visible') {
                    $(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+$t.p.id).slideDown("fast");
                    if($t.p.pager) {$($t.p.pager).slideDown("fast");}
                    if($t.p.toolbar[0]===true) {
                        if( $t.p.toolbar[1]=='both') {
                            $($t.grid.ubDiv).slideDown("fast");
                        }
                        $($t.grid.uDiv).slideDown("fast");
                    }
                    if($t.p.footerrow) $(".ui-jqgrid-sdiv","#gbox_"+$t.p.id).slideDown("fast");
                    $(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
                    $t.p.gridstate = 'visible';
                }
                
            });
        }
    }); })(jQuery);
    
    $(".history").jqGrid({        
        datatype: "local",
        height: 87,
        width: 500,
        colNames:['Action','Who', 'From Now', 'Timestamp'],
        colModel:[
            {name:'action', index:'action', width:150},
            {name:'who', index:'who', width:150},
            {name:'fromnow', index:'fromnow', width:150},
            {name:'when', index:'when', width:150}
        ],
        sortname: 'when',        
        sortorder: 'desc',        
        caption: "My Activity (click a row below to view more details)" 
    });
    
    var dont_expand_until_blur = false;
    
    $('.ui-jqgrid-titlebar-close').click(function() {
        dont_expand_until_blur = true;
    });
    
    $('.ui-jqgrid').hover(function() {
        if(!dont_expand_until_blur) {
            $('.history').setGridState('visible');
        }
    },function() {
        dont_expand_until_blur = false;
    });    

    for(var i=0;i<=mydata.length;i++) {
        $(".history").jqGrid('addRowData',i+1,mydata[i]);
        if(mydata[i] && mydata[i]['viewed'] == "false" && mydata[i]['action'].indexOf('to') == -1) {
            has_new_incoming_activity = true;
        }
    }
    if(has_new_incoming_activity) {
         $.facebox(
            '<div style="margin:-10px;height:30px; width: 500px; background-color:#627aad"></div>'+
            '<div style="padding-top:15px;height:100px;">'+
            '<br/>'+
            '<div style="font-weight: bold;color: #333;font-size: 15px;font-family:"lucida grande",tahoma,verdana,arial,sans-serif">'+
            'You have new incoming activity!'+
            '</div>'+
            '<br/>'+
            '<div style="color: #333;font-size: 15px;font-family:"lucida grande",tahoma,verdana,arial,sans-serif">'+
            'To view the new activity, just click its row in the table below.'+
            '</div>'
        );
    }
    $('.history tr').click(function() {
        setTimeout('$("#'+$(this).attr('id')+'").removeClass("ui-state-highlight");',1000);
        var data = mydata[$(this).attr('id')-1];
        show_fbml_dialog(
            data['action']+' '+data['who']+' '+data['fromnow']+'.',
            '<div style="padding-left:40px;padding-top:10px;"><h2>Message:</h2><br/><div style="width:600px; height:200px;overflow: auto;">'+data['message']+'</div></div>',
            700,    
            300
        ).show();
    });
    
    
    
    //load uservoice in a non blocking way in case they are down (which has happened)
    var js1 = document.createElement('script');
    js1.setAttribute("type","text/javascript");
    js1.setAttribute("src", 'http://uservoice.com/javascripts/widgets/tab.js');
    document.getElementsByTagName("head")[0].appendChild(js1);
    
    $('a[rel*=facebox]').facebox() 
    
});
